<template>
  <div>
    <el-drawer :visible.sync="detailDialogVisible" direction="rtl" size="66%" :before-close="handleClose"
      @opened="handleOpen" :with-header="false">
      <br />
      <br />
      <div class="content">
        <div v-if="this.dialogFlag == 'fppp'"><span class="titleClass">发票匹配</span>
          <span v-if="this.documentData.length == 1" style="margin-left: 20px;font-size: 15px;color: #f98446;">您本次选择了{{
            this.documentData.length }}条单据，可以选择多条发票数据与之匹配
            <span style="margin-left: 30px;color: red; font-weight: bold;">未税金额（原币）：{{ wsjehj }}
              &emsp;&emsp;&nbsp;税金（原币）：{{ sjhj }}</span></span>
          <span v-else style="margin-left: 20px;font-size: 15px;color: #f98446;">您本次选择了{{ this.documentData.length
          }}条单据，只可以选择一条发票数据与之匹配 <span style="margin-left: 30px;color: red; font-weight: bold;">未税金额（原币）：{{ wsjehj }}
              &emsp;&emsp;&nbsp;税金（原币）：{{ sjhj }}</span></span>
        </div>
        <div v-else>
          <span class="titleClass">发票匹配详情</span>
        </div>
        <br />
        <!-- 查询框 -->
        <div class="search-wrapper">
          <el-collapse accordion v-model="activeName">
            <el-collapse-item title="查询条件" name="1">
              <el-form ref="form" :model="searchParams" label-width="100px" class="queryForm" :inline="true" size="mini">
                <el-form-item label="开票日期" prop="entryDateRange">
                  <el-date-picker :clearable="false" v-model="searchParams.entryDateRange" type="daterange" align="right"
                    :unlink-panels="true" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期"
                    value-format="yyyy-MM-dd" :picker-options="pickerOptions"></el-date-picker>
                </el-form-item>
                <el-form-item label="发票号码">
                  <el-row>
                    <el-col :span="11"><el-input placeholder="请输入发票号码起" v-model="searchParams.invNrq" :clearable="true"
                        :maxlength="30" onkeyup="value=value.replace(/[^\d]/g,'')">
                      </el-input></el-col>
                    <el-col :span="2">&nbsp;&nbsp;&nbsp;--</el-col>
                    <el-col :span="11"><el-input placeholder="请输入发票号码止" v-model="searchParams.invNrz" :clearable="true"
                        :maxlength="30" onkeyup="value=value.replace(/[^\d]/g,'')">
                      </el-input></el-col>
                  </el-row>
                </el-form-item>
                <el-form-item label="供应商名称" v-if="this.dialogFlag == 'fppp'">
                  {{ this.supplierName }}
                </el-form-item>
                <el-form-item label="供应商名称" v-else>
                  <el-input placeholder="请输入供应商名称" v-model="searchParams.supplierName" :clearable="true" :maxlength="200">
                  </el-input>
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" size="mini" @click="searchFn()">查询</el-button>
                  <el-button type="info" @click="reset" size="mini">重置</el-button>
                </el-form-item>
              </el-form>

            </el-collapse-item>
          </el-collapse>
        </div>
        <!-- 按钮组件 -->
        <div>
          <div class="btns" v-if="this.dialogFlag == 'fppp'">
            <el-button type="primary" @click="sureFn()" size="small" style="margin-right: 10px;" :disabled="sureBtn"> 选择
            </el-button>
            <el-popconfirm title="确认退出发票匹配页面吗?" icon="el-icon-info" placement="left" confirm-button-text="确认"
              @confirm="handleClose()" cancel-button-text="取消">
              <el-button slot="reference" size="small" style="margin-top: 5px;">取消</el-button>
            </el-popconfirm>
          </div>
          <div class="toolBarClass" :style="`width:${toolBarWidth}`">
            <!-- <el-divider direction="vertical"></el-divider> -->
            <!-- <div style="float: left;"> -->
            <span style="font-size: 16px"><span v-if="this.dialogFlag == 'fppp'">已勾选发票</span>共 </span><span
              style="font-size: 15px; color: red">{{ tablelength }}</span><span style="font-size: 16px"> 条</span>
            <el-divider direction="vertical"></el-divider>
            <span style="font-size: 16px">金额：</span><span style="font-size: 15px; color: red">{{ totalje }}</span><span
              style="font-size: 16px"> 元</span>
            <el-divider direction="vertical"></el-divider>
            <span style="font-size: 16px">税额：</span><span style="font-size: 15px; color: red">{{ totalse }}</span><span
              style="font-size: 16px"> 元</span>
            <el-divider direction="vertical"></el-divider>
            <span style="font-size: 16px">价税合计：</span><span style="font-size: 15px; color: red">{{ totaljshj
            }}</span><span style="font-size: 16px"> 元</span>
            <span v-if="this.dialogFlag == 'fppp'">
              <el-input size="small" v-model="sroriginAmount" placeholder="原币金额"
                style="width: 200px; margin-left: 6%;margin-bottom:10px"
                onkeyup="value=value.replace(/^([0-9-]\d*\.?\d{0,2})?.*$/,'$1')">
              </el-input>
              <el-button type="primary" size="small" @click="ppOriginAmount" style="margin-left: 5px"
                :disabled="ppBtn">匹配</el-button>
            </span>
          </div>
        </div>
        <u-table :header-cell-style="{ background: '#F0F1F3', }" :data="tableData" ref="singleTable" highlight-current-row
          z header-align="center" align="center" max-height="550px" min-height="200px" @cell-click="clickRow"
          :big-data-checkbox="true" row-key="invId" use-virtual @selection-change="handleSelectionChange"
          :row-class-name="tableRowClassName">
          <u-table-column type="selection" width="55" align="center" />
          <u-table-column label="序号" type="index" width="55" align="center" />
          <u-table-column width="75" key="invType" prop="invType" header-align="center" align="center"
            :show-overflow-tooltip="true">
            <template slot="header">
              <allType-dialog></allType-dialog>
            </template>
            <template slot-scope="scope">
              <div v-if="scope.row.invType == '04' || scope.row.invType == '2'"><el-tag
                  size="mini">&nbsp;&nbsp;纸普&nbsp;&nbsp;</el-tag></div>
              <div v-if="scope.row.invType == '01' || scope.row.invType == '0'"><el-tag type="warning"
                  size="mini">&nbsp;&nbsp;纸专&nbsp;&nbsp;</el-tag></div>
              <div v-if="scope.row.invType == '10' || scope.row.invType == '51'"><el-tag type="success"
                  size="mini">&nbsp;&nbsp;电普&nbsp;&nbsp;</el-tag></div>
              <div v-if="scope.row.invType == '14'"><el-tag type="info" size="mini">通行费</el-tag></div>
              <div v-if="scope.row.invType == '03' || scope.row.invType == '41'"><el-tag type="warning"
                  size="mini">机动车</el-tag>
              </div>
              <div v-if="scope.row.invType == '11' || scope.row.invType == '10103'"><el-tag type="success"
                  size="mini">&emsp;卷&emsp;</el-tag></div>
              <div v-if="scope.row.invType == '15' || scope.row.invType == '10105'"><el-tag type="warning"
                  size="mini">二手车</el-tag>
              </div>
              <div v-if="scope.row.invType == '81' || scope.row.invType == '62'"><el-tag type="success"
                  size="mini">数电专</el-tag>
              </div>
              <div v-if="scope.row.invType == '82' || scope.row.invType == '61'"><el-tag type="danger"
                  size="mini">数电普</el-tag>
              </div>
              <div v-if="scope.row.invType == '08' || scope.row.invType == '8'"><el-tag
                  size="mini">&nbsp;&nbsp;电专&nbsp;&nbsp;</el-tag></div>
            </template>
          </u-table-column>
          <u-table-column prop="invCode" label="发票代码/发票号码" :show-overflow-tooltip="true" width="162px">
            <template slot-scope="scope">
              <span v-if="scope.row.einvNr != '' && scope.row.einvNr != null">
                <el-button type="text" size="small" title="点击复制" icon="el-icon-document-copy"
                  @click="handleCopyLink(scope.row.einvNr)"></el-button>
                <span style="color:#65B9FD; cursor: pointer;" @click="showInfo(scope.row)"> {{ scope.row.einvNr }}</span>
              </span>
              <div v-else>
                <el-button type="text" size="small" title="点击复制" icon="el-icon-document-copy"
                  @click="handleCopyLink(scope.row.invCode + ' - ' + scope.row.invNr)"></el-button>
                <span>{{ scope.row.invCode }}</span><br>
                <span style="color:#65B9FD; cursor: pointer;" @click="showInfo(scope.row)">{{ scope.row.invNr }}</span>
              </div>
            </template>
          </u-table-column>
          <u-table-column label="发票日期" prop="invDate" show-overflow-tooltip />
          <u-table-column label="销方名称" prop="sellerName" show-overflow-tooltip />
          <u-table-column label="销方税号" prop="sellerTax" show-overflow-tooltip />
          <u-table-column label="不含税金额" prop="invAmount" show-overflow-tooltip />
          <u-table-column label="税额" prop="taxAmount" show-overflow-tooltip />
          <u-table-column label="价税合计" prop="totalAmount" show-overflow-tooltip />
          <u-table-column label="原币金额" prop="originAmount" show-overflow-tooltip>
            <!-- <template slot-scope="scope">
              <el-input size="mini" ref="input" v-model="scope.row.originAmount" placeholder="原币金额"
                onkeyup="value=value.replace(/^([0-9-]\d*\.?\d{0,2})?.*$/,'$1')"></el-input>             
            </template> -->
          </u-table-column>
          <u-table-column label="发票备注" prop="memo" show-overflow-tooltip />
        </u-table>
        <!-- 分页页码 -->
        <!-- <div class="pageClass">
          <el-pagination :small="true" @size-change="handleSizeChange" @current-change="handleCurrentChange"
            :current-page="this.pageParams.pageIndex" :page-sizes="[25, 50, 75, 100]"
            :page-size="this.pageParams.pageSize" layout="total, sizes, prev, pager, next, jumper"
            :total="this.pageParams.total"></el-pagination>
        </div> -->
        <div style="margin-top: 50px;" v-if="this.docTableData.length != 0">
          <span style="font-size: 15px;font-weight: bold;"><span
              style="color: red;font-size: 20px;">*</span>当前发票存在其他匹配单据：</span>
          <el-table :header-cell-style="{ background: '#F0F1F3', }" :data="docTableData" ref="singleTable"
            highlight-current-row header-align="center" align="center" border>
            <el-table-column label="单据类型" prop="documentType" show-overflow-tooltip />
            <el-table-column label="单据号" prop="documentNr" show-overflow-tooltip />
            <!-- <el-table-column label="BG" prop="bg" show-overflow-tooltip /> -->
            <el-table-column label="单据时间" prop="documentDate" show-overflow-tooltip />
            <!-- <el-table-column label="供应商代码" prop="supplierCode" show-overflow-tooltip /> -->
            <el-table-column label="供应商名称" prop="supplierName" show-overflow-tooltip />
            <el-table-column label="国别" prop="country" show-overflow-tooltip />
            <!-- <el-table-column label="DN/CN" prop="dnCn" show-overflow-tooltip /> -->
            <el-table-column label="GRN" prop="grn" show-overflow-tooltip />
            <el-table-column label="币种" prop="currency" show-overflow-tooltip />
            <!-- <el-table-column label="汇率" prop="exchangeRate" show-overflow-tooltip /> -->
            <el-table-column label="未税金额（原币）" prop="originalCurrencyAmount" show-overflow-tooltip />
            <!-- <el-table-column label="未税金额（本币）" prop="localCurrencyAmount" show-overflow-tooltip /> -->
            <!-- <el-table-column label="税率" prop="taxRate" show-overflow-tooltip /> -->
            <el-table-column label="税金（原币）" prop="originalCurrencyTax" show-overflow-tooltip />
            <!-- <el-table-column label="税金（本币）" prop="localCurrencyTax" show-overflow-tooltip />
            <el-table-column label="验证状态" prop="validationStatus" show-overflow-tooltip />
            <el-table-column label="操作时间" prop="operationTime" show-overflow-tooltip />
            <el-table-column label="请求号" prop="requestNr" show-overflow-tooltip />
            <el-table-column label="匹配状态" prop="matchStatus" show-overflow-tooltip />
            <el-table-column label="回传状态" prop="feedbackStatus" show-overflow-tooltip />
            <el-table-column label="回传时间" prop="feedbackTime" show-overflow-tooltip /> -->
          </el-table>
        </div>
      </div>
    </el-drawer>
    <toll-dialog ref="tollDialog"></toll-dialog>
    <Einvoice-dialog ref="einvoiceDialog"></Einvoice-dialog>
    <detail-dialog ref="detailDialog"></detail-dialog>
    <car-dialog ref="carDialog"></car-dialog>
    <el-dialog title="提示" :visible.sync="innerDialog" width="25%" :append-to-body="true" :show-close="false"
      :closeOnClickModal="false" :closeOnPressEscape="false">
      <div style="margin-left:22px;">匹配失败： <span style="color:red;">{{ this.errMsg }}</span> </div>
      <div style="margin-left:15px;margin-top:35px" v-if="this.isInvAmount == 2">
        <el-form ref="invForm" :model="invParams" :inline="true" size="mini" :rules="formItemRules">
          <el-form-item label="发票金额：" required prop="invAmount">
            <el-input placeholder="请输入发票金额" v-model="invParams.invAmount" :clearable="true" :maxlength="200">
            </el-input>
          </el-form-item>
        </el-form>
      </div>
      <div style="margin-left:15px;margin-top:20px">是否进行强制匹配？</div>

      <span slot="footer" class="dialog-footer">
        <el-button @click="exitFn()" size="small">取 消</el-button>
        <el-button type="primary" @click="submitFn()" size="small" :disabled="sumbitBtn">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import moment from 'moment'
import { matchInvList, getInvInfo, getSum, docInvList, doMatch, forceMatch, getOtherDocument, ppOriginAmount } from '../js/zsdz.js'
import allInvType from '@/components/inv-type/allInvType.vue';
import tollInvDetaildialog from '@/components/invoiceStyle/tollInvDetaildialog.vue';
import allECInvDetaildialog from '@/components/invoiceStyle/allECInvDetaildialog.vue';
import detaildialog from '@/components/invoiceStyle/detaildialog.vue';
import carDetaildialog from '@/components/invoiceStyle/carDetaildialog.vue';
import baseSearch from '@/libs/baseSearch.js'
import { convertCurrency } from "@/libs/tools.js";
export default {
  components: {
    'allType-dialog': allInvType,
    'toll-dialog': tollInvDetaildialog,
    'Einvoice-dialog': allECInvDetaildialog,
    'detail-dialog': detaildialog,
    'car-dialog': carDetaildialog,

  },
  data() {
    return {
      detailDialogVisible: false,
      dialogFlag: '',
      pickerOptions: baseSearch.pickerOptions,
      activeName: '1',
      sureBtn: false,
      ppBtn: false,
      formLabelWidth: '120px',
      toolBarWidth: '100%',
      tableData: [],
      supplierName: '',
      documentData: [],
      multipleSelection: [],
      // 表格分页数据
      pageParams: {
        pageIndex: 1,
        pageSize: 25,
        total: 0,
      },
      searchParams: {
        entryDateRange: null,
        kprqq: '',
        kprqz: '',
        invNrq: '',
        invNrz: '',
        supplierName: '',
        documentId: '',
        pageSize: 25,
        pageIndex: 1,
      },
      tablelength: 0,
      totalje: 0.0,
      totalse: 0.0,
      totaljshj: 0.0,
      innerDialog: false,
      errMsg: '',
      isInvAmount: 0,
      matchParam: {
        documentIds: [],
        invoiceIds: [],
        invoiceAmount: 0
      },
      invParams: {
        invAmount: ''
      },
      sumbitBtn: false,
      formItemRules: {
        invAmount: [{ required: true, message: '发票金额不能为空', trigger: 'blur' }],
      },
      wsjehj: 0,
      sjhj: 0,
      docTableData: [],
      sroriginAmount: '',
    }
  },
  methods: {
    handleOpen() {
      this.ppBtn = false
      this.searchParams.supplierName = this.supplierName
      this.searchFn()
    },
    /**
      * 查询功能
      */
    searchFn() {
      this.searchParams.pageIndex = 1
      this.tablelength = 0
      this.totalse = 0.0
      this.totalje = 0.0
      this.totaljshj = 0.0
      var entryDate = this.searchParams.entryDateRange;
      if (entryDate != null && entryDate != "") {
        this.searchParams.kprqq = entryDate[0] + ' 00:00:00';
        this.searchParams.kprqz = entryDate[1] + ' 23:59:59';
      } else {
        this.searchParams.kprqq = "";
        this.searchParams.kprqz = "";
      }
      if (this.dialogFlag == 'fppp') {
        this.initTableData()
      } else {
        this.getDocInvList()
      }
    },
    // 查询重置功能
    reset() {
      this.searchParams = {
        entryDateRange: null,
        kprqq: '',
        kprqz: '',
        invNrq: '',
        invNrz: '',
        pageSize: 25,
        pageIndex: 1,
      }
    },
    initTableData() {
      matchInvList(this.searchParams).then((res) => {
        if (res.code == 0) {
          this.tableData = res.data
          if (this.tableData.length == 0) {
            this.$message({
              showClose: true,
              type: 'error',
              message: "暂无符合查询条件且未匹配的发票数据",
            })
          }
        } else {
          this.$message({
            type: 'error',
            message: res.message,
          })
        }
      })
    },
    async getDocInvList() {
      await docInvList(this.searchParams).then((res) => {
        if (res.code == 0) {
          this.tableData = res.data
          this.tablelength = this.tableData.length
          if (this.tablelength != 0) {
            this.getSum(this.tableData)
            if (this.tablelength == 1) {
              this.getOtherDocument(res.data[0].invId, this.searchParams.documentId)
            }

          }
        } else {
          this.$message({
            type: 'error',
            message: res.message,
          })
        }
      }).catch((e) => {
        this.$message({
          message: e,
          type: 'warning',
        })
      })
    },
    getSum(tableData) {
      var param = {}
      param.jisuan = Base64.encode(JSON.stringify(tableData))
      getSum(param).then((res) => {
        if (res.code == 0) {
          this.totalse = res.data.totalse
          this.totalje = res.data.totalje
          this.totaljshj = res.data.totaljshj
        } else {
          this.$message({
            type: 'warning',
            message: res.message,
          })
        }
      })
    },
    getOtherDocument(invId, documentId) {
      this.docTableData = []
      let param = {}
      param.invId = invId
      param.documentId = documentId
      getOtherDocument(param).then((res) => {
        if (res.code == 0) {
          this.docTableData = res.data
        } else {
          this.$message({
            type: 'error',
            message: res.message,
          })
        }
      }).catch((e) => {
        this.$message({
          message: e,
          type: 'warning',
        })
      })

    },

    //发票详情
    showInfo(row) {
      var param = {}
      param.invcode = row.invCode
      param.invnr = row.invNr
      param.eInvnr = row.einvNr
      getInvInfo(param).then((res) => {
        if (res.code == 0) {
          row = res.data
          if (row.invkind == '14') {
            this.$refs.tollDialog.invoiceForm.invcode = row.invcode
            this.$refs.tollDialog.invoiceForm.invnr = row.invnr
            this.$refs.tollDialog.invoiceForm.invdate = row.invdate
            this.$refs.tollDialog.invoiceForm.custname = row.custname
            this.$refs.tollDialog.invoiceForm.custtaxnr = row.custtaxnr
            this.$refs.tollDialog.invoiceForm.sellername = row.sellername
            this.$refs.tollDialog.invoiceForm.sellertaxnr = row.sellertaxnr
            this.$refs.tollDialog.invoiceForm.totalamount = row.totalamount
            if (row.totalamount.toString().indexOf("-") != -1) {
              this.$refs.tollDialog.invoiceForm.totalamountDX = "(负数)" + convertCurrency(row.totalamount.substring(1))
            } else {
              this.$refs.tollDialog.invoiceForm.totalamountDX = convertCurrency(row.totalamount)
            }
            this.$refs.tollDialog.invoiceForm.detailsList = row.list
            this.$refs.tollDialog.detailDialogVisible = true
          } else if (row.invkind == '81' || row.invkind == '82') {
            this.$refs.einvoiceDialog.invoiceForm.invnr = row.eInvnr
            this.$refs.einvoiceDialog.invoiceForm.invdate = row.invdate
            this.$refs.einvoiceDialog.invoiceForm.custname = row.custname
            this.$refs.einvoiceDialog.invoiceForm.custtaxnr = row.custtaxnr
            this.$refs.einvoiceDialog.invoiceForm.sellername = row.sellername
            this.$refs.einvoiceDialog.invoiceForm.sellertaxnr = row.sellertaxnr
            this.$refs.einvoiceDialog.invoiceForm.totalamount = row.totalamount
            this.$refs.einvoiceDialog.invoiceForm.memo = row.memo
            if (row.totalamount.toString().indexOf("-") != -1) {
              this.$refs.einvoiceDialog.invoiceForm.totalamountDX = "(负数)" + convertCurrency(row.totalamount.substring(1))
            } else {
              this.$refs.einvoiceDialog.invoiceForm.totalamountDX = convertCurrency(row.totalamount)
            }
            this.$refs.einvoiceDialog.invoiceForm.detailsList = row.list
            if (row.invkind == '62' || row.invkind == '81') {
              this.$refs.einvoiceDialog.invoiceTitle = "电子发票（增值税专用发票）"
            } else {
              this.$refs.einvoiceDialog.invoiceTitle = "电子发票（普通发票）"
            }
            this.$refs.einvoiceDialog.detailDialogVisible = true
          } else if (row.invkind == '41') {
            this.$refs.carDialog.invoiceTitle = "机动车销售统一发票"
            this.$refs.carDialog.invoiceForm.invdate = moment(row.invdate).format('YYYY-MM-DD')
            this.$refs.carDialog.invoiceForm.invcode = row.invcode
            this.$refs.carDialog.invoiceForm.invnr = row.invnr
            this.$refs.carDialog.invoiceForm.certificate = row.invoiceCar.certificate
            this.$refs.carDialog.invoiceForm.certificateimport = row.invoiceCar.certificateimport
            this.$refs.carDialog.invoiceForm.idNo = row.invoiceCar.custidnr
            this.$refs.carDialog.invoiceForm.custname = row.invoiceCar.custname
            this.$refs.carDialog.invoiceForm.custtaxnr = row.invoiceCar.custtaxnr
            this.$refs.carDialog.invoiceForm.issuer = row.invoiceCar.drawer
            this.$refs.carDialog.invoiceForm.enginenr = row.invoiceCar.enginenr
            this.$refs.carDialog.invoiceForm.factorymodel = row.invoiceCar.factorymodel
            this.$refs.carDialog.invoiceForm.inspectionnr = row.invoiceCar.inspectionnr
            this.$refs.carDialog.invoiceForm.invamount = row.invoiceCar.invamount
            this.$refs.carDialog.invoiceForm.limitpeople = row.invoiceCar.limitpeople
            this.$refs.carDialog.invoiceForm.machineno = row.invoiceCar.machineno
            this.$refs.carDialog.invoiceForm.productplace = row.invoiceCar.productplace
            this.$refs.carDialog.invoiceForm.salerAddress = row.invoiceCar.salerAddress
            this.$refs.carDialog.invoiceForm.salerBankAccount = row.invoiceCar.salerBankAccount
            this.$refs.carDialog.invoiceForm.salerBankName = row.invoiceCar.salerBankName
            this.$refs.carDialog.invoiceForm.salerPhone = row.invoiceCar.salerPhone
            this.$refs.carDialog.invoiceForm.sallername = row.invoiceCar.sallername
            this.$refs.carDialog.invoiceForm.sallertaxnr = row.invoiceCar.sallertaxnr
            this.$refs.carDialog.invoiceForm.taxamount = row.invoiceCar.taxamount
            this.$refs.carDialog.invoiceForm.taxrate = row.invoiceCar.taxrate
            this.$refs.carDialog.invoiceForm.taxbureaucode = row.invoiceCar.taxbureaucode
            this.$refs.carDialog.invoiceForm.taxbureauname = row.invoiceCar.taxbureauname
            this.$refs.carDialog.invoiceForm.taxrecords = row.invoiceCar.taxrecords
            this.$refs.carDialog.invoiceForm.tonnage = row.invoiceCar.tonnage
            this.$refs.carDialog.invoiceForm.totalamount = row.invoiceCar.totalamount
            this.$refs.carDialog.invoiceForm.totalamountDX = convertCurrency(row.invoiceCar.totalamount)
            this.$refs.carDialog.invoiceForm.vehiclenr = row.invoiceCar.vehiclenr
            this.$refs.carDialog.invoiceForm.vehicletype = row.invoiceCar.vehicletype
            this.$refs.carDialog.detailDialogVisible = true
          } else {
            if (row.invkind == '04') {
              this.$refs.detailDialog.invoiceTitle = '增值税普通发票'
            } else if (row.invkind == '01') {
              this.$refs.detailDialog.invoiceTitle = '增值税专用发票'
            } else if (row.invkind == '10') {
              this.$refs.detailDialog.invoiceTitle = '增值税电子普通发票'
            } else if (row.invkind == '08') {
              this.$refs.detailDialog.invoiceTitle = '增值税电子专用发票'
            }
            this.$refs.detailDialog.invoiceForm.invcode = row.invcode
            this.$refs.detailDialog.invoiceForm.invnr = row.invnr
            this.$refs.detailDialog.invoiceForm.invdate = row.invdate
            this.$refs.detailDialog.invoiceForm.custname = row.custname
            this.$refs.detailDialog.invoiceForm.custtaxnr = row.custtaxnr
            this.$refs.detailDialog.invoiceForm.custaddrtel = row.custaddrtel
            this.$refs.detailDialog.invoiceForm.custbankacct = row.custbankacct
            this.$refs.detailDialog.invoiceForm.selleraddresstel = row.selleraddresstel
            this.$refs.detailDialog.invoiceForm.sellerbankacct = row.sellerbankacct
            this.$refs.detailDialog.invoiceForm.sellername = row.sellername
            this.$refs.detailDialog.invoiceForm.sellertaxnr = row.sellertaxnr
            this.$refs.detailDialog.invoiceForm.totalamount = row.totalamount
            this.$refs.detailDialog.invoiceForm.memo = row.memo
            this.$refs.detailDialog.invoiceForm.payee = row.payee
            this.$refs.detailDialog.invoiceForm.checker = row.checker
            this.$refs.detailDialog.invoiceForm.issuer = row.issuer
            if (row.totalamount.toString().indexOf("-") != -1) {
              this.$refs.detailDialog.invoiceForm.totalamountDX = "(负数)" + convertCurrency(row.totalamount.substring(1))
            } else {
              this.$refs.detailDialog.invoiceForm.totalamountDX = convertCurrency(row.totalamount)
            }
            this.$refs.detailDialog.invoiceForm.detailsList = row.list
            this.$refs.detailDialog.detailDialogVisible = true
          }
        } else if (res.code != 0) {
          this.$message({
            message: res.message,
            type: 'warning',
          })
        }
      })
    },
    clickRow(row) {
      this.$refs.singleTable.toggleRowSelection([
        {
          row: row
        }
      ])
      // this.$refs.singleTable.toggleRowSelection(row)
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
      this.tablelength = this.multipleSelection.length
      if (this.tablelength != 0) {
        this.getSum(this.multipleSelection)
      } else {
        this.totalse = 0.0
        this.totalje = 0.0
        this.totaljshj = 0.0
      }
    },
    tableRowClassName({ row, rowIndex }) {
      //把每一行的索引放进
      row.rowIndex = rowIndex
    },
    //原币金额匹配
    ppOriginAmount() {
      this.ppBtn = true
      if (this.tableData == [] || this.tableData.length == 0) {
        this.$message({
          message: '无发票列表数据',
          type: 'warning',
        })
        this.ppBtn = false
        return
      }
      if (this.sroriginAmount == null || this.sroriginAmount == '' || this.sroriginAmount == 0 || this.sroriginAmount == 0.00 || this.sroriginAmount == 0.0) {
        this.$message({
          message: '原币金额不可为空，且不可以为0',
          type: 'warning',
        })
        this.ppBtn = false
        return
      }
      var selected = this.multipleSelection
      if (selected == null || selected == '' || selected.length <= 0) {
        this.$message({
          message: '至少选择一张发票',
          type: 'warning',
        })
        this.ppBtn = false
        return
      }
      let invLength = selected.length
      let docLength = this.documentData.length
      if (docLength != 1) {//多张单据
        if (invLength != 1) {
          this.$message({
            message: '您本次选择了 ' + docLength + ' 条单据，只可以选择一条发票数据与之匹配',
            type: 'warning',
          })
          this.ppBtn = false
          return
        }
      }
      let yzIndex = []
      let bfgIndex = []
      var selectedIndex = []
      let invIds = new Array()
      for (var i = 0; i < invLength; i++) {
        let invData = selected[i]
        let rowIndex = invData.rowIndex
        if (!(invData.originAmount == null || invData.originAmount == '' || invData.originAmount == 0)) {
          if (invData.originAmount != this.sroriginAmount) {
            yzIndex.push(rowIndex + 1)
            bfgIndex.push(rowIndex)
          }
        }
        let p = {}
        p.rowData = invData
        p.rowIndex = rowIndex
        selectedIndex.push(p)
        invIds.push(invData.invId)
      }
      var param = {}
      param.invoiceIds = invIds
      param.originAmountSearch = this.sroriginAmount
      if (yzIndex.length != 0) {
        this.$confirm('第：' + JSON.stringify(yzIndex) + "行发票备注中存在原币金额，且与输入金额不符，是否要覆盖？", '提示', {
          confirmButtonText: '覆盖',
          cancelButtonText: '不覆盖',
          type: 'warning',
        })
          .then((_) => {
            param.confirmStatus = '1'
            this.pp(param, '1', selectedIndex, bfgIndex)
          })
          .catch((_) => {
            console.log("不覆盖")
            if (yzIndex.length == invLength) {
              this.$message({
                message: '您本次选择了 ' + invLength + ' 条发票，全都有原币金额，您选择了不覆盖，系统不做处理',
                type: 'warning',
              })
              this.ppBtn = false
              return
            }
            param.confirmStatus = '0'
            this.pp(param, '0', selectedIndex, bfgIndex)
          })
      } else {
        this.pp(param, '1', selectedIndex, bfgIndex)
      }
    },
    pp(param, flag, selectedIndex, bfgIndex) {
      ppOriginAmount(param).then((res) => {
        if (res.code == 0) {
          this.editTable(flag, selectedIndex, bfgIndex)
        } else {
          this.ppBtn = false
          this.$message({
            type: 'error',
            message: res.message,
          })
        }
      }).catch(error => {
        this.ppBtn = false
        this.$message({
          type: 'error',
          message: error,
        })
      })
    },
    editTable(flag, selectedIndex, bfgIndex) {
      if (flag == '1') {//覆盖
        for (let i = 0; i < selectedIndex.length; i++) {
          let p = selectedIndex[0]
          var data = p.rowData
          data.originAmount = this.sroriginAmount
          this.$set(this.tableData, p.rowIndex, data)
        }
      } else {
        for (var i = 0; i < selectedIndex.length; i++) {
          var hava = false
          var p = selectedIndex[0]
          var rowIndex = p.rowIndex
          for (var k = 0; k < bfgIndex.length; k++) {
            if (bfgIndex[k] == rowIndex) {
              hava = true
              break
            }
          }
          if (!hava) {
            var data = p.rowData
            data.originAmount = this.sroriginAmount
            this.$set(this.tableData, rowIndex, data)
          }
        }
      }
      this.ppBtn = false
    },
    //保存方法
    async sureFn() {
      this.errMsg = ''
      this.isInvAmount = 0
      this.sureBtn = true
      if (this.tableData == [] || this.tableData.length == 0) {
        this.$message({
          message: '无发票列表数据',
          type: 'warning',
        })
        this.sureBtn = false
        return
      }
      // var selected = this.$refs.singleTable.selection
      var selected = this.multipleSelection

      if (selected == null || selected == '' || selected.length <= 0) {
        this.$message({
          message: '至少选择一张发票',
          type: 'warning',
        })
        this.sureBtn = false
        return
      }
      let invLength = selected.length
      let docLength = this.documentData.length
      if (docLength != 1) {//多张单据
        if (invLength != 1) {
          this.$message({
            message: '您本次选择了 ' + docLength + ' 条单据，只可以选择一条发票数据与之匹配',
            type: 'warning',
          })
          this.sureBtn = false
          return
        }
      }
      let ar = new Array()
      for (var i = 0; i < docLength; i++) {
        ar.push(this.documentData[i].documentId)
      }
      let invIds = new Array()
      let originAmountList = new Array()
      for (var i = 0; i < invLength; i++) {
        invIds.push(selected[i].invId)
        originAmountList.push(selected[i].originAmount)
      }

      this.matchParam.documentIds = ar
      this.matchParam.invoiceIds = invIds
      this.matchParam.originAmountList = originAmountList
      this.matchParam.invoiceAmount = 0
      await doMatch(this.matchParam).then((res) => {
        if (res.code == 0) {
          // if (res.data == 1 || res.data == 2) {//存在匹配失败的 需要调用强制匹配接口
          //   this.sureBtn = false
          //   this.errMsg = res.message
          //   this.isInvAmount = res.data
          //   this.innerDialog = true
          // } else {
          if (res.data == 3) {
            this.$confirm(res.message, '提示', {
              confirmButtonText: '继续',
              cancelButtonText: '取消',
              type: 'warning',
            })
              .then((_) => {
                this.matchParam.confirmStatus = '1'
                doMatch(this.matchParam).then((res) => {
                  if (res.code == 0) {
                    this.$message({
                      message: res.message,
                      type: 'success',
                    })
                    this.handleClose()
                  } else {
                    this.$message({
                      message: res.message,
                      type: 'warning',
                    })
                    this.sureBtn = false
                  }
                }).catch((e) => {
                  this.sureBtn = false
                  this.$message({
                    message: e,
                    type: 'warning',
                  })
                })
              })
              .catch((_) => {
                this.$message({
                  message: '您取消了本次单据匹配操作',
                  type: 'warning',
                })
                this.sureBtn = false
              })
          } else {
            this.$message({
              message: res.message,
              type: 'success',
            })
            this.handleClose()
          }
        } else if (res.code != 0) {
          this.sureBtn = false
          this.$message({
            message: res.message,
            type: 'warning',
          })
        }
      }).catch((e) => {
        this.sureBtn = false
        this.$message({
          message: e,
          type: 'warning',
        })
      })
    },
    submitFn() {
      this.sumbitBtn = true
      if (this.isInvAmount == 2) {
        this.$refs.invForm.validate(async (valid) => {
          if (valid) {
            this.matchParam.invoiceAmount = this.invParams.invAmount
            this.forceMatch()
          } else {
            this.sumbitBtn = false
            return false
          }
        })
      } else {
        this.forceMatch()
      }
    },
    forceMatch() {
      forceMatch(this.matchParam).then((res) => {
        if (res.code == 0) {
          this.$message({
            message: '强制匹配成功',
            type: 'success',
          })
          this.handleClose()
        } else {
          this.sumbitBtn = false
          this.$message({
            message: res.message,
            type: 'warning',
          })
        }
      }).catch((e) => {
        this.$message({
          message: e,
          type: 'warning',
        })
      })
    },
    exitFn() {
      this.innerDialog = false
      this.invParams.invAmount = ''
      this.sumbitBtn = false
      this.searchFn()
    },
    handleClose() {
      this.closedFn()
    },
    closedFn() {
      this.sureBtn = false
      this.supplierName = ''
      this.tableData = []
      this.documentData = []
      this.matchParam = {
        documentIds: [],
        invoiceIds: [],
        invoiceAmount: 0
      }
      this.invParams = {
        invAmount: ''
      }
      this.errMsg = ''
      this.isInvAmount = 0
      if (this.dialogFlag == 'fppp') {
        this.$emit('matchClose', null)
      }
      this.docTableData = []
      this.detailDialogVisible = false
    },
    ////分页
    handleSizeChange(val) {
      this.searchParams.pageSize = val
      this.initTableData()
    },
    handleCurrentChange(val) {
      this.searchParams.pageIndex = val
      this.initTableData()
    },
    handleCopyLink(val) {
      let _this = this
      this.$copyText(val).then(
        function (e) {
          _this.$message({
            showClose: true,
            message: '复制成功',
            type: 'success',
          })
        },
        function (e) {
          _this.$message({
            showClose: true,
            message: '复制失败，请手动复制',
            type: 'error',
          })
        }
      )
    },
  },
}
</script>

<style scoped>
.content {
  width: 98%;
  min-width: 1200px;
  margin-left: 10px;

}

.titleClass {
  font-size: 18px;
  color: #333;
  font-weight: 500;
  padding-left: 5px;
  border-left: 3px solid #0077ff;
  margin-bottom: 16px;
  line-height: 14px;
  margin-left: 10px;
}

.search-wrapper {
  text-align: left;
  box-shadow: 2px 2px 4px 2px rgba(0, 0, 0, 0.12), 0 0 6px 0 rgba(0, 0, 0, 0.04);
  margin-bottom: 25px;
}

.search-wrapper ::v-deep .el-collapse-item__content {
  padding-bottom: 0px !important;
}

.search-wrapper ::v-deep .el-collapse-item__header {
  padding-left: 15px !important;
}

.btns {
  float: left;
}

.toolBarClass {
  overflow: hidden;
  float: right;

  margin-top: 10px;
}

.toolBarClass /deep/ .el-divider--vertical {
  height: 2em;
}
</style>

